const express = require("express");
const router = express.Router();
const { userModel } = require("../models/model");

// 初始化两个账号
(async () => {
  const users = [
    { username: "user1", password: "123456" },
    { username: "customer_service", password: "123456" },
  ];
  for (const u of users) {
    const exist = await userModel.findOne({ username: u.username });
    if (!exist) {
      await userModel.create(u);
    }
  }
})();

// 用户注册
router.post("/register", async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json({ code: 1, msg: "用户名和密码不能为空" });
  }
  const exist = await userModel.findOne({ username });
  if (exist) {
    return res.status(400).json({ code: 1, msg: "用户名已存在" });
  }
  const user = await userModel.create({ username, password });
  res.json({ code: 0, data: { userId: user._id, username: user.username } });
});

// 用户登录
router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json({ code: 1, msg: "用户名和密码不能为空" });
  }
  const user = await userModel.findOne({ username, password });
  if (!user) {
    return res.status(400).json({ code: 1, msg: "用户名或密码错误" });
  }
  res.json({ code: 0, data: { userId: user._id, username: user.username } });
});

module.exports = router;
